package cn.wjdiankong.levideo.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.ss.android.common.applog.GlobalContext;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import cn.wjdiankong.levideo.R;
import cn.wjdiankong.levideo.data.LevideoData;
import cn.wjdiankong.levideo.database.LocalStorage;
import cn.wjdiankong.levideo.dialog.ConfirmDialog;
import cn.wjdiankong.levideo.fragment.BaseFragment;
import cn.wjdiankong.levideo.fragment.DouyinFragment;
import cn.wjdiankong.levideo.fragment.HuoshanFragment;
import cn.wjdiankong.levideo.fragment.KuaishouFragment;
import cn.wjdiankong.levideo.fragment.MiaopaiFragment;
import cn.wjdiankong.levideo.utils.Const;
import cn.wjdiankong.levideo.utils.FileUtils;
import cn.wjdiankong.levideo.utils.UIUtil;
import cn.wjdiankong.levideo.utils.UmengReportUtils;
import cn.wjdiankong.levideo.utils.Utils;
import cn.wjdiankong.levideo.view.PagerSlidingTabStrip;
import cn.wjdiankong.levideo.view.PagerSlidingTabStrip.ViewPageChangeListener;
import cn.wjdiankong.levideo.view.SmileyLoadingView;

@SuppressLint("NewApi")
public class LocalVideoActivity extends BaseActivity {

	private PagerSlidingTabStrip tabs;
	private ViewPager pager;
	private MyPagerAdapter adapter;

	private ArrayList<String> titles = new ArrayList<String>();
	private List<BaseFragment> fragmentList = new ArrayList<BaseFragment>();
	private int curPosition = 0;

	private SmileyLoadingView loadingView;
	private View noDataView, contentView;

	private List<LevideoData> douyinList = new ArrayList<LevideoData>();
	private List<LevideoData> huoshanList = new ArrayList<LevideoData>();
	private List<LevideoData> kuaishouList = new ArrayList<LevideoData>();
	private List<LevideoData> miaopaiList = new ArrayList<LevideoData>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_localvideo);
		init();
	}

	private void init(){
		initView();
		initData();
	}

	protected void initView(){
		super.initView();
		loadingView = (SmileyLoadingView) findViewById(R.id.loading_view);
		noDataView = findViewById(R.id.nodata_layout);
		contentView = findViewById(R.id.content_view);
		tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
		pager = (ViewPager) findViewById(R.id.pager);
		setTitle("保存视频");
		setLeftImg(R.drawable.back_icon);
		showLoadingView();
	}

	protected void initData(){
		super.initData();
		new AsyncTask<Void, Void, Void>(){
			@Override
			protected Void doInBackground(Void... params) {
				getLocalData();
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				initFragment();
			}
		}.execute();
	}

	private void getLocalData(){
		List<LevideoData> douyinVideoDataList = LocalStorage.getInstance().getLevideoDataList(Const.VIDEO_TYPE_DOUYIN);
		List<LevideoData> huoshanVideoDataList = LocalStorage.getInstance().getLevideoDataList(Const.VIDEO_TYPE_HUOSHAN);
		List<LevideoData> kuaishouVideoDataList = LocalStorage.getInstance().getLevideoDataList(Const.VIDEO_TYPE_KUAISHOU);
		List<LevideoData> miaopaiVideoDataList = LocalStorage.getInstance().getLevideoDataList(Const.VIDEO_TYPE_MIAOPAI);

		File[] douyinFiles = FileUtils.getLocalVideo(Const.VIDEO_TYPE_DOUYIN);
		File[] huoshanFiles = FileUtils.getLocalVideo(Const.VIDEO_TYPE_HUOSHAN);
		File[] kuaishouFiles = FileUtils.getLocalVideo(Const.VIDEO_TYPE_KUAISHOU);
		File[] miaopaiFiles = FileUtils.getLocalVideo(Const.VIDEO_TYPE_MIAOPAI);

		if(douyinVideoDataList != null && douyinVideoDataList.size() > 0 && douyinFiles.length > 0){
			for(File file : douyinFiles){
				String name = file.getAbsolutePath();
				for(LevideoData data : douyinVideoDataList){
					if(name.equals(data.videoPlayUrl)){
						douyinList.add(data);
					}
				}
			}
		}

		if(huoshanVideoDataList != null && huoshanVideoDataList.size() > 0 && huoshanFiles.length > 0){
			for(File file : huoshanFiles){
				String name = file.getAbsolutePath();
				for(LevideoData data : huoshanVideoDataList){
					if(name.equals(data.videoPlayUrl)){
						huoshanList.add(data);
					}
				}
			}
		}

		if(kuaishouVideoDataList != null && kuaishouVideoDataList.size() > 0 && kuaishouFiles.length > 0){
			for(File file : kuaishouFiles){
				String name = file.getAbsolutePath();
				for(LevideoData data : kuaishouVideoDataList){
					if(name.equals(data.videoPlayUrl)){
						kuaishouList.add(data);
					}
				}
			}
		}

		if(miaopaiVideoDataList != null && miaopaiVideoDataList.size() > 0 && miaopaiFiles.length > 0){
			for(File file : miaopaiFiles){
				String name = file.getAbsolutePath();
				for(LevideoData data : miaopaiVideoDataList){
					if(name.equals(data.videoPlayUrl)){
						miaopaiList.add(data);
					}
				}
			}
		}
	}

	private void initFragment(){
		if(douyinList.size() == 0 && kuaishouList.size() == 0 && huoshanList.size() == 0 && miaopaiList.size() == 0){
			showNoDataView();
			return;
		}
		
		if(douyinList.size() > 0){
			titles.add("抖音");
			DouyinFragment douyinF = DouyinFragment.newInstance(0, "抖音", Const.VIDEO_TYPE_DOUYIN);
			douyinF.isLocal = true;
			douyinF.setVideoData(douyinList);
			fragmentList.add(douyinF);
			Utils.sortLevideoData(douyinList);
		}

		if(kuaishouList.size() > 0){
			titles.add("快手");
			KuaishouFragment kuaishouF = KuaishouFragment.newInstance(1, "快手", Const.VIDEO_TYPE_KUAISHOU);
			kuaishouF.isLocal = true;
			kuaishouF.setVideoData(kuaishouList);
			Utils.sortLevideoData(kuaishouList);
			fragmentList.add(kuaishouF);
		}

		if(huoshanList.size() > 0){
			titles.add("火山");
			HuoshanFragment huoshanF = HuoshanFragment.newInstance(2, "火山", Const.VIDEO_TYPE_HUOSHAN);
			huoshanF.isLocal = true;
			huoshanF.setVideoData(huoshanList);
			Utils.sortLevideoData(huoshanList);
			fragmentList.add(huoshanF);
		}

		if(miaopaiList.size() > 0){
			titles.add("秒拍");
			MiaopaiFragment miaopaiF = MiaopaiFragment.newInstance(3, "秒拍", Const.VIDEO_TYPE_MIAOPAI);
			miaopaiF.isLocal = true;
			miaopaiF.setVideoData(miaopaiList);
			Utils.sortLevideoData(miaopaiList);
			fragmentList.add(miaopaiF);
		}

		showContentView();

		initTab();
	}

	/**
	 * 初始化tab
	 */
	private void initTab(){
		adapter = new MyPagerAdapter(getSupportFragmentManager());
		pager.setAdapter(adapter);
		pager.setOffscreenPageLimit(4);
		int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
		pager.setPageMargin(pageMargin);
		pager.addOnPageChangeListener(adapter);
		tabs.setIndicatorColor(Const.theme_bg);
		tabs.setIndicatorHeight(UIUtil.dip2px(GlobalContext.getContext(), 2));
		tabs.setTextSize(UIUtil.dip2px(GlobalContext.getContext(), 14));
		tabs.setUnderlineHeight(0);
		tabs.setViewPager(pager);
		tabs.setViewPageChangeListener(new ViewPageChangeListener(){
			@Override
			public void changeViewPage(int position) {
				curPosition = position;
			}});
		pager.setCurrentItem(curPosition, true);
	}

	private void showLoadingView(){
		loadingView.start();
		loadingView.setVisibility(View.VISIBLE);
		contentView.setVisibility(View.GONE);
		noDataView.setVisibility(View.GONE);
	}

	private void showContentView(){
		loadingView.stop();
		loadingView.setVisibility(View.GONE);
		contentView.setVisibility(View.VISIBLE);
		noDataView.setVisibility(View.GONE);
		setRightImg(R.drawable.delete_icon);
	}

	private void showNoDataView(){
		loadingView.stop();
		loadingView.setVisibility(View.GONE);
		contentView.setVisibility(View.GONE);
		noDataView.setVisibility(View.VISIBLE);
	}

	public class MyPagerAdapter extends FragmentPagerAdapter implements OnPageChangeListener {

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return titles.get(position);
		}

		@Override
		public int getCount() {
			return fragmentList.size();
		}

		@Override
		public Fragment getItem(int position) {
			return fragmentList.get(position);
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int postion) {
		}

	}

	public static void startDefault(Context context){
		Intent intent = new Intent(context, LocalVideoActivity.class);
		context.startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == VideoPlayerActivity.CODE_RESULT){
			int position = data.getIntExtra("del_position", -1);
			int type = data.getIntExtra("del_type", -1);
			if(position >= 0 && type >= 0){
				for(BaseFragment fragment : fragmentList){
					if(fragment.type == type){
						fragment.removeData(position);
						UIUtil.showShortHintToast(getApplicationContext(), "删除成功");
						return;
					}
				}
			}
		}
	}

	@Override
	protected void clickLeftImg(){
		finish();
	}

	@Override
	protected void clickRightImg(){
		UmengReportUtils.report(UmengReportUtils.LOCALVIDEO_DELETE_ALL);
		final ConfirmDialog dialog = new ConfirmDialog(this);
		dialog.setContentTxt("您将删除所有保存的本地视频，确定是否继续操作？").setLeftTxt("取消", new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dimiss();
			}
		}).setRightTxt("确定", new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dimiss();
				//删除全部
				boolean douyinSucc = true, huoshanSucc = true, kuaishouSucc = true, miaopaiSucc = true;
				if(douyinList.size() > 0){
					douyinSucc = FileUtils.isDeleteSucc(Const.VIDEO_TYPE_DOUYIN);
				}
				if(huoshanList.size() > 0){
					huoshanSucc = FileUtils.isDeleteSucc(Const.VIDEO_TYPE_HUOSHAN);
				}
				if(kuaishouList.size() > 0){
					kuaishouSucc = FileUtils.isDeleteSucc(Const.VIDEO_TYPE_KUAISHOU);
				}
				if(miaopaiList.size() > 0){
					miaopaiSucc = FileUtils.isDeleteSucc(Const.VIDEO_TYPE_MIAOPAI);
				}
				if(douyinSucc && huoshanSucc && kuaishouSucc && miaopaiSucc){
					UIUtil.showShortHintToast(getApplicationContext(), "删除成功！");
					finish();
				}else{
					UIUtil.showShortHintToast(getApplicationContext(), "部分内容删除成功！");
				}
			}
		}).show();
	}
	
	@Override
	protected String getPageName() {
		return "local_video";
	}

}